package org.jeecg.modules.zcgl.tencent.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.zcgl.enums.WxMpErrorMsgEnum;
import org.jeecg.modules.zcgl.tencent.config.IWxPayConfig;
import org.jeecg.modules.zcgl.tencent.config.JSSign;
import org.jeecg.modules.zcgl.tencent.enums.ErrorCodeEnum;
import org.jeecg.modules.zcgl.tencent.vo.WxSdkConfigParam;
import org.jeecg.modules.zcgl.tencent.vo.WxSdkConfigResp;
import org.jeecg.modules.zcgl.tencent.vo.JsApiTicketResponse;
import org.jeecg.modules.zcgl.tencent.service.IWxPayService;
import org.jeecg.modules.zcgl.tencent.service.IWxTokenService;
import org.jeecg.modules.zcgl.tencent.service.http.HttpService;
import org.jeecg.modules.zcgl.util.WxWebUrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WxPayServiceImpl extends AbstractWxService implements IWxPayService {

//    private static ConcurrentHashMap<String, String> TICKET_MAP = new ConcurrentHashMap<>();
    private static final String JSAPI_TICKET = "jsapi_ticket";
//    private static final String EXPIRES_IN = "expires_in";

    @Autowired
    private IWxPayConfig iWxPayConfig;
    @Autowired
    private IWxTokenService wxTokenService;
    @Autowired
    private HttpService httpService;

    @Autowired
    @Lazy
    private RedisUtil redisUtil;

    @Override
    public WxSdkConfigResp wxSdkConfig(WxSdkConfigParam param) {
        log.info("wxSdkConfig, start, param={}", param);
        if (param == null) {
            throw new JeecgBootException(ErrorCodeEnum.SYS_PARAMETER_ERROR.getMessage());
        }
        WxSdkConfigResp resp = new WxSdkConfigResp();
        Map<String, String> result = JSSign.sign(this.getJSAPITicket(true), param.getUrl());

        resp.setAppId(iWxPayConfig.getAppID());
        resp.setNonceStr(result.get("nonceStr"));
        resp.setSignature(result.get("signature"));
        resp.setTimestamp(result.get("timestamp"));
        log.info("wxSdkConfig, end, resp={}", resp);
        return resp;
    }

    private String getJSAPITicket(boolean first) {
        String JsApiTicket = null;

        Object js = redisUtil.get(JSAPI_TICKET);
        if (js != null){
            JsApiTicket = js.toString();
            return JsApiTicket;
        }

        String accessToken = wxTokenService.getWxToken();

        // params
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put(WxWebUrl.UrlParam.ACCESS_TOKEN, accessToken);
        JsApiTicketResponse response = null;
        try {
            response = httpService.get(this.fmtReqWebsUrl(WxWebUrl.GET_TICKET, paramMap), JsApiTicketResponse.class);
            if (response != null && first
                    && (response.getErrcode() == WxMpErrorMsgEnum.CODE_42001.getCode()
                    || response.getErrcode() == WxMpErrorMsgEnum.CODE_40001.getCode()
                    || response.getErrcode() == WxMpErrorMsgEnum.CODE_40014.getCode())){
                wxTokenService.refreshtWxToken();
                return getJSAPITicket(false);
            }
        } catch (Exception e) {
            log.error("getJSAPITicket() exception. ", e);
        }

        if (response != null && response.getErrcode() == WxMpErrorMsgEnum.CODE_0.getCode()) {
            JsApiTicket = response.getTicket();
            Integer expiresIn = response.getExpires_in();
            redisUtil.set(JSAPI_TICKET, JsApiTicket, expiresIn-10);
        }
        log.info("getJSAPITicket() end, JsApiTicket={}", JsApiTicket);
        return JsApiTicket;
    }
}
